package com.nomi.blog.config;

import com.nomi.blog.exception.UnauthorizedException;
import com.nomi.blog.utils.JwtUtils;
import com.nomi.blog.utils.UserContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Value("${jwt.secret}")
    private String jwtSecret;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 临时跳过鉴权测试
        // return true;

        // 放行 OPTIONS 请求（CORS 预检）
        if (request.getMethod().equals("OPTIONS")) {
            return true;
        }

        // 从请求头中获取token
        String token = request.getHeader("Authorization");
        System.out.println("token:"+token);

        // 如果token为空，抛出未授权异常
        if (token == null || token.isEmpty()) {
            throw new UnauthorizedException("请先登录");
        }

        //验证token
        Long userId = JwtUtils.getUserId(token, jwtSecret);
        System.out.println("userId："+userId);
        if(userId == null){
            throw new UnauthorizedException("无效的token");
        }

        //将用户ID存入ThreadLocal，方便后续使用
        UserContext.setCurrentUserId(userId);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清除ThreadLocal中的用户ID
        UserContext.removeCurrentUserId();
    }
}
